package com.mydubbo.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.mydubbo.invoker.Invoker;
import com.mydubbo.loadbalance.LoadBalance;
import com.mydubbo.loadbalance.RandomLoadBalance;
import com.mydubbo.proxy.BaseProxyFactory;
import com.mydubbo.proxy.CglibProxyFactory;
import com.mydubbo.registry.Registry;
import com.mydubbo.registry.ZookeeperRegistry;
import com.mydubbo.rpc.Server;
import com.mydubbo.rpc.netty.NettyServer;
import com.mydubbo.util.IpUtil;

import lombok.Setter;

public class MyDubboReferStarter {
	
	@Setter private Registry registry;
	@Setter private LoadBalance loadBalance;
	@Setter private Server server;
	@Setter private BaseProxyFactory proxyFactory;
	//从zookeeper中读出的服务对应的提供者
	private final ConcurrentHashMap<String, List<String>> serviceMap = new ConcurrentHashMap<>();
	
	public void refreshServiceMap(String className, List<String> serverIps) {
		serviceMap.put(className, serverIps);
		System.out.println(serviceMap);
	}
	
	public List<String> getServiceServer(String className) {
		System.out.println(serviceMap + "," + className);
		return serviceMap.get(className);
	}
	
	public ConcurrentHashMap<String, List<String>> getServiceMap() {
		return serviceMap;
	}
	
	public void addBeanRefer(Class<?> clazz) {
		serviceMap.put(clazz.getName(), new ArrayList<>());
	}
	
	public void start() {
		if(registry==null) {
			registry = new ZookeeperRegistry();
		}
		if(loadBalance==null) {
			loadBalance = new RandomLoadBalance();
		}
		if(server==null) {
			server = new NettyServer();
		}
		if(proxyFactory==null) {
			proxyFactory = new CglibProxyFactory();
		}
		proxyFactory.setInvoker(new Invoker(loadBalance, server));
		
		String clientIp = IpUtil.getLocalIp();
		for(String className : serviceMap.keySet()) {
			registry.subscribe(new MyDubboRefer(className, clientIp));
		}
	}
	
	public Object getProxy(Class<?> clazz) {
		return proxyFactory.getProxy(clazz);
	}
	
	private MyDubboReferStarter() {};
	
	public static MyDubboReferStarter getInstance() {
		return Builder.instance;
	}
	
	private static class Builder {
		private static MyDubboReferStarter instance = new MyDubboReferStarter();
	}

}
